<template>
  <div>
    <TopFilter
      :list="topFilterList"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>

    <FilterTable
      ref="table"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      :onRowSelectChange="selectChangeHandle"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-edit" :click="allot" :auth-list="auths" auth-mark="/api/cyxdms.clue/clueauditDisc/setDistributionAuditDists">再分配</multiuse-button>
      </template>
    </FilterTable>
    <!-- 明细页面 -->
    <Drawer
      :visible.sync="visible"
      title="客户信息"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"

    >
      <div class="father">
        <div class="son">
          <el-button size="small" :disabled="formData.actionId?false:true" type="primary" @click="followUp">跟进</el-button>
          <el-button size="small" type="primary" @click="continueBuy">续购</el-button>
        </div>
      </div>
      <custsDetail :type="handleType" :rowData="formData" @close="closeHandler" />
    </Drawer>
    <BaseDialog
      :visible.sync="followVisible"
      title="基盘跟进"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <followModal :type="handleType" :baseType='baseType' :rowData="formData" @close="closeHandler_follow" />
    </BaseDialog>
    <Drawer
      :visible.sync="customerVisible"
      title="新增潜客"
      :width="1000"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <cluesModel :type="handleType" :rowData="formData" @close="closeHandler_Customer" />
    </Drawer>

    <el-dialog
      :visible.sync="consultVisible"
      title="再分配"
      :type="consultHandleType"
      :rowData="consultFormData"
      width="30%"
      style="text-align: center;">
        <!-- <el-select v-model="checkNames" @change="handleCheckedNamesChange" clearable placeholder="请选择">
          <el-option
            v-for="item in consults"
            :key="item.employeeId"
            :label="item.employeeName"
            :value="item.employeeId">
          </el-option>
        </el-select>
        <div
          :style="{
            marginTop:'20px',
            textAlign: 'center'
          }"
        > -->
        <FormPanel
          ref="formPanel"
          :list="formList"
          :cols="1"
          labelWidth="90"
          :isSubmitBtn="false"
        />
          <el-button @click="consultcloseVisible">取 消</el-button>
          <AjaxButton type="primary" :click="consultHandler">确 定</AjaxButton>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryBaseList,
  getBaseInfoById,
  redistributionIds,
  setDistributionAuditDists
} from '@/api/potenCus/basePlate/cust1Manage';
import {
  queryEmployees,
} from '@/api/potenCus/customer/potenCusManage';
import { dictionary } from '@/utils/dictMixin';
import { formatDates, formatDat } from '@/utils/validate';
import custsDetail from './custsDetail';
import followModal from './../basePlateFollow/modal'
import cluesModel from './../../customer/potenCusManage/cluesModel';
import { authority } from '@/utils/authMixin';
import {getUserInfoByRolePosition,getUserInfo} from '@/api/potenCus/customer/exhibition'
import { getDataType } from '@/assets/js/auth';
import Cookies from 'js-cookie';
export default {
  name: 'cust1Manage',
  mixins: [dictionary,authority],
  components: {
    custsDetail,
    followModal,
    cluesModel
  },
  data() {
    return {
      baseType:"manage",
      dataType : getDataType('dataType'),
      topFilterList: this.createTopFilters(),
      formList:this.createFormList(),
      fetchParams: {},
      selectedRows: [], //选中列表中的行
      visible: false,
      consultVisible: false,   //分配
      consultFormData: {},    //分配
      formData: {},
      formData_follow: {},
      followVisible: false,   //跟进
      formData_Customer: {},
      customerVisible: false,   //跟进
      fetchApi: queryBaseList,
      columns: this.createTableColumns(),
      handleType: '',
      conf:{ show: '明细' },
      consultHandleType: '',
      checkNames: '',
      consults:[],

    };
  },
  created() {
    this.init();
    this.getEmployeeList()
  },
  methods: {
    createFormList() {
      return [
        {
          type: 'SELECT',
          label: '再分配',
          fieldName: 'customerType',
          placeholder: '请选择',
          itemList: [],
          width: 150,
        }
      ];
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '潜客名称',
          fieldName: 'potentialcustomerName',
          placeholder: '潜客名称'
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          placeholder: '客户名称'
        },
        {
          type: 'INPUT',
          label: '客户电话',
          fieldName: 'phone',
          placeholder: '客户电话',
        },
        {
          type: 'INPUT',
          label: '联系人',
          fieldName: 'contactNmae',
          placeholder: '联系人',
        },
        {
          type: 'INPUT',
          label: '联系人电话',
          fieldName: 'contactPhone',
          placeholder: '联系人电话',
        },
        {
          type: 'RANGE_DATE',
          label: '首次购车日期',
          fieldName: 'bargainDate|bargainDateEnd',
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'VIN',
          placeholder: 'VIN',
        },
        {
          type: 'SELECT',
          label: '客户等级',
          fieldName: 'level',
          placeholder: '请选择',
          itemList: this.createDictList('7049'),
        },
        {
          type: 'SELECT',
          label: '销售顾问',
          fieldName: 'consultant',
          placeholder: '请选择',
          itemList: []
        },
      ];
    },
    createTableColumns() {
      return [
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 60,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <multiuse-button size="mini" type="text" onClick={() => this.showHandle(props.row)} auth-list={this.auths} auth-mark={'/api/cyxdms.clue/clueauditDisc/auditDistPotentialDetail/?actionId=${id}&potentialCustomersId=${potentialCustomersId}&clueType=${clueType}'}>
                  明细
                </multiuse-button>
              </div>
            );
          }
        },
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '客户编号',
          dataIndex: 'potentialCustomerNo',
          sorter: true,
          filter: true,
          width: 150,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '客户类型',
          dataIndex: 'customerType',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('1523'),
          render: props => {
            return <span>{this.createDictText(props.row.customerType, '1523')}</span>;
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '客户电话',
          dataIndex: 'phone',
          sorter: true,
          width:200,
          //filter: true,
          filterType: 'input'
        },
        {
          title: '联系人',
          dataIndex: 'contactName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '联系人电话',
          dataIndex: 'contactPhone',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },

        {
          title: '开票地址',
          dataIndex: 'billingAddress',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '客户等级',
          dataIndex: 'level',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'checkbox',
          filterItems: this.createDictList('7049'),
          render: props => {
            return <span>{this.createDictText(props.row.level, '7049')}</span>;
          }
        },
        {
          title: '首次购车日期',
          dataIndex: 'bargainDate',
          sorter: true,
          width: 150,
          align: 'center',
          render: props =>{
            return <span>{ formatDat(props.row.bargainDate) }</span>
          }
        },
        {
          title: '已购车辆(台)',
          dataIndex: 'purchased',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '续购(台)',
          dataIndex: 'renewal',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '转介绍(台)',
          dataIndex: 'introduction',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
        {
          title: '销售顾问',
          dataIndex: 'consultantName',
          sorter: true,
          filter: true,
          align: 'center',
          filterType: 'input',
        },
      ];
    },
    async init(){
        // 查询所属顾问
      /* await getUserInfo().then(res => {
          if(res.resultCode == 200){
            this.userId=res.data.userInfo.userId
            let param = {
              companyId:res.data.userInfo.companyId,
              positionCode:10061015
            };
            getUserInfoByRolePosition(param).then(res => {
              if(res.resultCode == 200){
                // this.RolePosition=res.data.map(x => ({ value: x.userId, text: x.employeeName ,orgId:x.orgId}))
                // this.RolePosition=_.uniqBy(this.RolePosition,'value')
                // console.log(this.RolePosition,"this.RolePosition")
                // this.topFilterList.find(item=>item.fieldName == "consultant").itemList = this.RolePosition
              }else{
                this.$message.error('获取人员列表失败!');
              }
            })
          }else{
            this.$message.error('获取当前登录用户信息失败!');
          }
        }); */
        if(Cookies.get('baseNO')){
          this.fetchParams.contactPhone =Cookies.get('baseNO')
          this.topFilterList.find(item=>item.fieldName == "contactPhone").initialValue =Cookies.get('baseNO')
        }

        let roleType = this.dataType === 'clue' ? '10061012':'10061012,10061015';
        this.getConsultant(1,roleType).then((result) => {
          // console.log('顾问列表:' , result);
          this.consults = result;
          // this.consultsList = result
          this.RolePosition= result
          this.topFilterList.find(item=>item.fieldName == "consultant").itemList= result
        })
    },
    selectChangeHandle(rows) {
      this.selectedRows = rows;
    },
    async getEmployeeList() {
      const res = await queryEmployees();
      // console.log('顾问', res)
      if (res.resultCode === 200) {
        // this.topFilterList[7].itemList = res.data.map(x => ({ value: x.userId, text: x.employeeName }));
        // this.consults = res.data;
        this.formList.find(item=>item.fieldName == "customerType").itemList=res.data.map(x => ({ value: x.userId, text: x.employeeName }));
      }
    },
    async saveEmployee() {
      console.log('选中行',this.selectedRows)
      console.log('选中顾问',this.formList[0].initialValue)
      let params={
        consultantBasal:this.formList[0].initialValue,
        potentialCustomers:[]
      }
      this.selectedRows.map(x=>{
        params.potentialCustomers.push(x.potentialCustomersId)
      })
      setDistributionAuditDists(params).then(res=>{
          if(res.resultCode == 200){
            this.$message.success('分配成功');
            this.consultVisible = false;
            this.fetchParams = { ...this.fetchParams };
          }
      })
      // this.checkNames.map(x=>{
      //   userIds+=x.userId+','
      // })
      // let data = {
      //   "clueRecordIdDTOList": this.selectedRows,
      //   "userIds": userIds
      // }
      // const res = await saveConsultantName(data);
      // console.log('保存顾问', res)
      // if (res.resultCode === 200) {
      //   this.consultcloseVisible()
      // }
    },
    consultcloseVisible(){
      this.checkNames = ''
      this.selectedRows = []
      this.consultVisible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    consultHandler(){
      this.saveEmployee()
    },
    // 再分配
    allot(row) {
      this.checkNames = ''
      if(!this.selectedRows.length){
        this.$message.info('请先选基盘客户');
      } else {
        this.consultVisible = true;

      }
    },
    async showHandle(row){
      // console.log('明细row', row)
      // const res = await getBaseInfoById(2507, row.potentialCustomersId, 70241002)
      // console.log('明细id', res)
      this.handleType = 'show';
      this.formData = row;
      this.visible = true;
      this.showHandler()

    },
    // 选择顾问
    handleCheckedNamesChange(value) {
      // console.log('当前所选:' , value);
      this.checkNames = value
    },
    // 跟进
    followUp(){
      this.handleType = 'add';
      this.followVisible = true;
    },
    // 续购
    continueBuy(){
      this.handleType = 'addForbase';
      this.customerVisible = true;
    },
    changeHandle(val) {
      console.log(this.fetchParams,"this.fetchParams")
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    showHandler() {
      this.dialogTitle = `基盘管理${this.conf[this.handleType]}`;
      this.visible = true;
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_follow(val, type) {
      this.followVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },
    closeHandler_Customer(val, type) {
      this.customerVisible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    },



  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  deactivated() {
    Cookies.set('baseNO',"")
  },
  destroyed() {
    Cookies.set('baseNO',"")
  },
};
</script>

<style lang="less" scoped>
.father{
  width: 380px;
  height: auto;
  position: relative;
  float: right;
}
.son{
  position: absolute;
  top: -5px;
  right: 10px;
  z-index: 2;
}

</style>
